import Taro from '@tarojs/taro'
export const baseURL = "http://101.37.76.80:8899/kcwxy";

export interface ApiReturn {
  data: any
  statusCode: number
}

export const login = (code) => {
  return request('POST', '/app/onLogin', { code }).then((res: ApiReturn) => {
    Taro.setStorageSync('token', res)
  })
}
const authorize = (data: any) => {
  return request('POST', '/app/authorize', data).then((res: ApiReturn) => {
    console.log(res);
  })
}
export const getToken = () => {
  Taro.showModal({
    title: '提示',
    content: '请确认授权',
    success: function (res) {
      if (res.confirm) {
        Taro.getUserProfile({
          desc: '用于完善会员资料',
          success: (res) => {
            // @ts-ignore
            const { encryptedData, iv, rawData, signature, userInfo } = res
            const data = { encryptedData, iv, rawData, signature, userInfoPO: userInfo }
            authorize(data).then(res => {
              Taro.login().then(res => {
                const { code } = res
                login(code)
              })
              Taro.showToast({
                title: '为了保证使用正常，请前往个人中心绑定手机号码',
                icon: 'none',
                duration: 5000
              })
            })
          }
        })
      }
    }
  })

}
const reqUtils = (method, url, data, resolve) => {
  const token = Taro.getStorageSync('token')
  Taro.request({
    url: `${baseURL}${url}`,
    complete: (res) => { },
    data: data,
    dataType: 'json',
    mode: "cors",
    fail: (res) => {
      Taro.showToast({
        title: '请求失败',
        icon: 'none',
        duration: 2000
      })
    },
    header: { 'Content-Type': 'application/json', "Authorization": token },
    method: method,
    responseType: 'text',
    success: (res: ApiReturn) => {
      if (res.statusCode > 200) {
        Taro.showToast({
          // @ts-ignore
          title: res.data.message || res.data.error,
          icon: 'none',
          duration: 2000
        })
      }
      resolve(res.data)
    }
  })
}
export const request = (method, url, data) => new Promise((resolve, reject) => {
  // console.log(data);
  Taro.checkSession({
    success: function () {
      reqUtils(method, url, data, resolve)
    },
    fail: function () {
      // session_key 已经失效，需要重新执行登录流程
      Taro.login().then(res => {
        const { code } = res
        login(code).then(() => {
          reqUtils(method, url, data, resolve)
        })
      })
    }
  })
})


const uploadFileUtils = (url: string, path: string, resolve, fileName = 'files') => {
  const token = Taro.getStorageSync('token')
  Taro.uploadFile({
    url: `${baseURL}${url}`,
    filePath: path,
    name: fileName,
    header: { 'content-type': 'multipart/form-data', 'Authorization': token },
    // formData: { 'token': token },
    success: (res) => {
      // console.log(res);
      if (res.errMsg === "uploadFile:ok") {
        const data = JSON.parse(res.data)
        resolve(data)
      } else {
        Taro.showToast({
          // @ts-ignore
          title: '文件上传失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    fail: () => {
      Taro.showToast({
        // @ts-ignore
        title: '文件上传失败',
        icon: 'none',
        duration: 2000
      })
    },
  })
}

export const uploadFilerequest = (url, path, fileName = 'files') => new Promise((resolve, reject) => {
  // console.log(data);
  Taro.checkSession({
    success: function () {
      uploadFileUtils(url, path, resolve, fileName)
    },
    fail: function () {
      // session_key 已经失效，需要重新执行登录流程
      Taro.login().then(res => {
        const { code } = res
        login(code).then(() => {
          uploadFileUtils(url, path, resolve)
        })
      })
    }
  })
})